package test4_16.demo02;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TCPSeverDoubleTest {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        try {
            //创建端口
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("创建服务器端口");

            //分配，等待连接，accept阻塞方法 没有连接一直等待
            Socket socket = serverSocket.accept();
            System.out.println("服务器与客户端连接成功");

            //获取客户端数据，转成字符输出流,并封装成缓冲流
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            System.out.println("服务器端接受数据");

            //创建服务端获取数据
            PrintWriter pw = new PrintWriter(socket.getOutputStream());

            //读取数据并输出
            new Thread(() -> {
                String line;
                try {
                    while ((line = br.readLine()) != null) {
                        System.out.println("客户端说：" + line);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();

            //向客服端发送数据
            new Thread(() -> {
                try {
                    while (true) {
                        String message = scanner.nextLine();
                        pw.println(message);
                        pw.flush();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
